import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import {store} from '@/store/index.js'
import { getToken } from '@/utils/auth'
import router from '../router'

// 创建axios实例
let service = axios.create({
        baseURL: 'http://120.79.211.38:8000/api', // api的base_url
        timeout: 5000 // 请求超时时间
    })
    // request拦截器
service.interceptors.request.use(config => {
    if (getToken('Token')) {
        config.headers = {
            'Authorization': 'Bearer ' + getToken('Token'), //携带权限参数
        };
    }
    return config
}, error => {
    Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
    response => {
        /**
         * code:200,接口正常返回;
         */
        const res = response.data
        if (res.code !== 200) {
         
                if (res.code == 401){
                    return Promise.reject('error')
                }else{
                    Message({
                        message: res.msg,
                        type: 'error',
                        duration: 5 * 1000
                    })
                }
        } else { // res.code === 200,正常返回数据
            return response.data
        }
    },
    error => {
        Message({
            message: "登录失败请重新登录",
            type: 'error',
            duration: 5 * 1000
        })
        store.commit('LOGOUT');
        router.push('/login');
    }
)

export default service